#!/usr/bin/php
<?php

// This script should be in ZendFramework/standard/branches/user/salomonbrys/Zend_Socket
define('ZFLIBPATH', '/home/salomon/Downloads/appsrc/ZendFramework/standard/trunk/library/');

define('PWD', realpath(dirname(__FILE__)));

set_include_path(
	get_include_path()
	. PATH_SEPARATOR . realpath(ZFLIBPATH)							// Zend Framework
	. PATH_SEPARATOR . realpath(PWD . '/../Zend_Tokenizer/library')	// Zend Tokenizer
	. PATH_SEPARATOR . realpath(PWD . '/library')					// Zend Socket
);


if (!isset($argv[1]))
{
	echo "Need an argument: 'udpclient', 'udpserver', 'tcpclient', 'tcpserver'\n";
}
elseif ($argv[1] == "udpclient")
{
	require_once 'Zend/Socket/Udp.php';
	$socket = new Zend_Socket_Udp;
	$socket->connect('127.0.0.1', 42424);
	$socket->write("Hello, world\n");
	echo $socket->getRead(true, true);
	$socket->write("I love that Zend Socket Extension\n");
	echo $socket->getRead(true, true);
	$socket->write("Oh yeah beaby, I really do !\n");
	echo $socket->getRead(true, true);
}
else if ($argv[1] == "udpserver")
{
	require_once 'Zend/Socket/Udp.php';
	$socket = new Zend_Socket_Udp;
	$socket->bind('127.0.0.1', 42424);
	while (42)
	{
		$socket->read();
		$tab = $socket->getRead(true);
		var_dump($tab);
		foreach ($tab as $addr => $txt)
			$socket->write('I acknoledge reception of your: ' . $txt, $addr);
	}
}
elseif ($argv[1] == "tcpclient")
{
	require_once 'Zend/Socket/Tcp.php';
	$socket = new Zend_Socket_Tcp();
	$socket->connect('127.0.0.1', 42424);
	while ($socket->read())
	{
		echo $socket->getRead();
		$socket->write('OK: ' . $socket->getRead(true));
	}
}
elseif ($argv[1] == "tcpserver")
{
	require_once 'Zend/Socket/Tcp.php';
	require_once 'Zend/Socket/Tcp/Connection/Abstract.php';
	require_once 'Zend/Socket/Tcp/Server.php';
	require_once 'Zend/Tokenizer/String/Line.php';

	class MyTcpConnection extends Zend_Socket_Tcp_Connection_Abstract
	{
		public function __construct(Zend_Tokenizer_Interface $socket)
		{
			parent::__construct(new Zend_Tokenizer_String_Line($socket, true));
		}

		public function onRegister(Zend_Socket_Tcp_Server $server)
		{
			echo $this->Socket()->getFullName() . ": REGISTER\n";
			parent::onRegister($server);
			$this->Socket()->writeLater("Hello world !\n");
			$this->Server()->registerTick(microtime(true) + 0.5, array($this, 'sendPing'));
		}

		public function onUnregister()
		{
			echo $this->Socket()->getFullName() . ": UNREGISTER\n";
			parent::onUnregister();
		}

		public function onToken()
		{
			$text = $this->Tokenizer()->getToken();
			echo $this->Socket()->getFullName() . ": TEXT(".strlen((binary)$text)."): " . $text . "\n";
		}

		public function sendPing()
		{
			$this->Socket()->writeLater("Ping ".microtime()." !\n");
			$this->Server()->registerTick(microtime(true) + 0.5, array($this, 'sendPing'));
		}
	}

	$server = new Zend_Socket_Tcp_Server('MyTcpConnection', 42424);
	$server->loop();
}
else
{
	echo "Unknown argument\n";
}
